route.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { pick } from "lodash";
  2. import { NextResponse } from "next/server";
  3. import { WLEDClient } from "wled-client";
  4. import automation from "data/automation.json";
  5. const action = async ({ id, client, on }) => {
  6. let wled;
  7. let errors = [];
  8. try {
  9. console.log("connect to", client);
  10. wled = new WLEDClient(client); // setup a connection to the client
  11. await wled.init(); // init the connection
  12. } catch (err) {
  13. console.log("connect error", err.message);
  14. errors.push({ error: err.message, type: "connect", client: client });
  15. }
  16. try {
  17. console.log("set preset to", id);
  18. await wled.setPreset(id); // set the preset
  19. // await wled.setPreset(id); // set it again
  20. } catch (err) {
  21. console.log("preset error", err.message);
  22. errors.push({ error: err.message, type: "preset", client: client, id: id });
  23. }
  24. try {
  25. console.log("set power to", on);
  26. if (on) await wled.turnOn(); // turn off the lights
  27. else await wled.turnOff(); // turn off the lights
  28. } catch (err) {
  29. console.log("power error", err.message);
  30. errors.push({ error: err.message, type: "power", client: client, on });
  31. }
  32. try {
  33. await wled.refreshState();
  34. } catch (err) {
  35. console.log("state refresh", err.message);
  36. errors.push({ error: err.message, type: "refreshState", client: client });
  37. }
  38. return {
  39. ...pick(wled?.state || {}, ["on", "brightness", "presetId", "udpSync"]),
  40. errors
  41. };
  42. };
  43. export async function GET(req, { params }) {
  44. let promises = [];
  45. let id = params?.id || null;
  46. try {
  47. if (!id) throw new Error("No id specified");
  48. let clients = (automation?.[id] && Object.keys(automation?.[id])) || [];
  49. if (!clients) throw new Error("No clients for id", id);
  50. for (let client of clients) {
  51. promises.push(action({ id, client, ...automation?.[id]?.[client] }));
  52. }
  53. } catch (err) {
  54. return NextResponse.json({ error: err?.message }, { status: 500 });
  55. }
  56. return Promise.allSettled(promises)
  57. .then((results) => {
  58. console.log("results", results);
  59. return NextResponse.json(results?.map((o) => o?.value));
  60. })
  61. .catch((err) => {
  62. return NextResponse.json({ error: err?.message }, { status: 500 });
  63. });
  64. }